import time
import logging
import os
from fastapi import Request
import asyncio
from logging.handlers import RotatingFileHandler

# 获取当前文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 构建日志目录相对路径，相对于项目根目录
log_dir = os.path.join(current_dir, '..', 'logs')
# 确保日志目录存在
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 构建日志文件路径
log_file_path = os.path.join(log_dir, 'faceApi.log')

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        # 日志文件最大 5MB，保留 5 个备份文件
        RotatingFileHandler(log_file_path, encoding='utf-8', maxBytes=1024 * 1024 * 5, backupCount=5),
        logging.StreamHandler()  # 日志输出到控制台
    ]
)


async def write_log(message, level=logging.INFO):
    if level == logging.ERROR:
        logging.error(message)
        return
    if level == logging.WARNING:
        logging.warning(message)
        return
    if level == logging.INFO:
        logging.info(message)
        return
    if level == logging.DEBUG:
        logging.debug(message)
        return
    if level == logging.CRITICAL:
        logging.critical(message)
        return


# 添加中间件记录请求日志
async def log_requests(request: Request, call_next):
    start_time = time.time()
    # 记录请求时间
    request_time = time.strftime("%Y-%m-%d %H:%M:%S")
    try:
        # 读取请求参数
        if request.method in ["POST", "PUT"]:
            request_body = await request.body()
            try:
                request_params = request_body.decode("utf-8")
            except UnicodeDecodeError:
                request_params = "无法解码的请求体"
        else:
            request_params = str(request.query_params)

        response = await call_next(request)

        # 计算耗时
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)

        # 读取返回参数
        response_body = b""
        async for chunk in response.body_iterator:
            response_body += chunk
        try:
            response_params = response_body.decode("utf-8")
        except UnicodeDecodeError:
            response_params = "无法解码的响应体"

        # 重新构造响应
        from fastapi.responses import Response
        response = Response(
            content=response_body,
            status_code=response.status_code,
            headers=dict(response.headers),
            media_type=response.media_type
        )

        # 异步记录日志
        log_message = (
            f"请求路径: {request.url.path}, 返回参数: {response_params}, 耗时: {formatted_process_time}ms"
        )
        asyncio.create_task(write_log(log_message))

        return response
    except Exception as e:
        # 计算耗时
        process_time = (time.time() - start_time) * 1000
        formatted_process_time = '{0:.2f}'.format(process_time)
        error_message = (
            f"请求路径: {request.url.path}, 请求参数: {request_params}, 错误信息: {str(e)}, 耗时: {formatted_process_time}ms "
        )
        asyncio.create_task(write_log(error_message, logging.ERROR))
        raise
